package com.zhuhjay.common.base.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhuhjay.common.base.exception.ServerErrorException;

/**
 * @author ZhuHJay
 * @date 2023/2/25 0:57
 */
public class JacksonUtils {

    private static final ObjectMapper MAPPER;
    static {
        MAPPER = SpringContextHolder.getBean(ObjectMapper.class);
    }

    public static String writeValueAsString(Object value) {
        try {
            return MAPPER.writeValueAsString(value);
        } catch (Exception e) {
            throw new ServerErrorException("JSON序列化失败", e);
        }
    }

    public static <T> T readValue(String content, Class<T> valueType) {
        try {
            return MAPPER.readValue(content, valueType);
        } catch (Exception e) {
            throw new ServerErrorException("JSON反序列化失败", e);
        }
    }

    public static <T> T readValue(String content, TypeReference<T> valueType) {
        try {
            return MAPPER.readValue(content, valueType);
        } catch (Exception e) {
            throw new ServerErrorException("JSON反序列化失败", e);
        }
    }

}
